package com.mive.controller;

import com.mive.encache.CacheService;
import com.mive.entity.User;
import com.mive.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
@RequestMapping("/cache.do")
public class CacheController {

    private Logger logger = LoggerFactory.getLogger( CacheController.class );

    @Autowired
    private CacheService cacheService;
    @Autowired
    private UserService userService;

    @RequestMapping(value = "getByCache" ,method = RequestMethod.GET)
    public String getByCache(){
        Long startTime = System.currentTimeMillis();
        long timestamp = this.cacheService.getByCache();
        Long endTime = System.currentTimeMillis();
        System.out.println("耗时："+(endTime - startTime));
        return timestamp +"";
    };

    @RequestMapping(value = "saveCache", method = RequestMethod.GET)
    public void save(){
        this.cacheService.save();
    }

    @RequestMapping(value = "deleteCache", method = RequestMethod.GET)
    public void delete(){
        this.cacheService.delete();
    }

    @RequestMapping(value = "ehcacheTest", method = RequestMethod.GET)
    public String EhcacheTest() throws Exception {
        logger.info( "ehcache缓存测试！" );
        logger.info( "@@@@@生成第一个用户" );
        String uuid = UUID.randomUUID().toString();
        String uuid1 = uuid.substring( 0,8 )+uuid.substring( 9,13 )
                +uuid.substring( 14,18 )+uuid.substring( 19,23 )+uuid.substring( 24 );
        User user1 = new User(  );
        user1.setName("张三");
        user1.setAge(18);
        user1.setUuid( uuid1 );
        if (userService.save( user1 ) == 0){
            throw new Exception( "插入对象失败！" );
        }
        logger.info( "====第一次查询===" );
        logger.info( "<===="+userService.findByUuid( user1.getUuid() )+"====>" );
        logger.info( "====缓存查询====" );
        logger.info( "<===="+userService.findByUuid( user1.getUuid() )+"====>" );

        logger.info( "@@@@@修改用户数据" );
        User user2 = new User(  );
        user2.setName( "李四-update" );
        user2.setAge( 20 );
        user2.setId( user1.getId() );
        user2.setUuid( user1.getUuid() );
        logger.info( "开始更新：" +userService.update( user2 ));
        logger.info( "====第二次查询===" );
        logger.info( "<===="+userService.findByUuid( user2.getUuid() )+"====>" );

        logger.info( "@@@@@删除用户数据" );
        logger.info( "开始删除" );
        userService.delete( user2.getUuid());
        logger.info( "====第三次查询===" );
        logger.info( "<===="+userService.findByUuid( user2.getUuid() )+"====>" );
        return "success";
    }
}
